<template>
  <div class="photography-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex flex-col space-y-4">
          <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
              摄影作品
            </h1>
            <div class="flex items-center gap-4">
              <el-button
                type="primary"
                :icon="Camera"
                @click="$router.push('/user/photos')"
              >
                我发布的摄影
              </el-button>
              <el-button
                type="primary"
                :icon="Plus"
                @click="showCreatePhotoDialog = true"
              >
                发布作品
              </el-button>
            </div>
          </div>
          <p class="text-gray-600 dark:text-gray-400">
            探索贵港最美打卡地，定格精彩瞬间
          </p>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 筛选区域 -->
          <div
            class="filter-section bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <div class="flex flex-wrap gap-4">
              <!-- 分类筛选 -->
              <el-select
                v-model="filters.category"
                placeholder="打卡类型"
                clearable
                class="!w-[140px]"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>

              <!-- 景区筛选 -->
              <el-select
                v-model="filters.spotId"
                placeholder="关联景点"
                clearable
                class="!w-[140px]"
              >
                <el-option
                  v-for="spot in spots"
                  :key="spot.id"
                  :label="spot.name"
                  :value="spot.id"
                />
              </el-select>

              <!-- 排序方式 -->
              <el-select
                v-model="filters.sortBy"
                placeholder="排序方式"
                class="!w-[140px]"
              >
                <el-option
                  v-for="sort in sortOptions"
                  :key="sort.value"
                  :label="sort.label"
                  :value="sort.value"
                />
              </el-select>

              <!-- 搜索框 -->
              <el-input
                v-model="searchQuery"
                placeholder="搜索打卡地点"
                class="!w-[200px]"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 打卡地列表 -->
          <div
            class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
            v-loading="loading"
          >
            <div
              v-for="spot in displayedPhotoSpots"
              :key="spot.id"
              class="spot-card group bg-white dark:bg-gray-800 rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 cursor-pointer"
              @click="handleSpotClick(spot)"
            >
              <div class="relative">
                <el-image
                  :src="spot.image"
                  class="w-full aspect-[4/3] object-cover transform group-hover:scale-105 transition-transform duration-500"
                />
                <div class="absolute top-4 right-4">
                  <el-tag
                    :type="getTagType(spot.type)"
                    effect="light"
                    class="!border-0"
                    >{{ spot.type }}</el-tag
                  >
                </div>
                <div
                  class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent p-4"
                >
                  <h3 class="text-white text-lg font-medium mb-1">
                    {{ spot.name }}
                  </h3>
                  <div class="flex items-center text-white/80 text-sm">
                    <el-icon class="mr-1"><Timer /></el-icon>
                    <span>最佳拍摄：{{ spot.bestTime }}</span>
                  </div>
                </div>
              </div>
              <div class="p-4">
                <div class="flex items-center justify-between mb-3">
                  <div
                    class="flex items-center text-sm text-gray-500 dark:text-gray-400"
                  >
                    <el-icon class="mr-1"><Camera /></el-icon>
                    <span>{{ formatNumber(spot.checkInCount) }}次打卡</span>
                  </div>
                  <div
                    class="flex items-center text-sm text-gray-500 dark:text-gray-400"
                  >
                    <el-icon class="mr-1"><Picture /></el-icon>
                    <span>{{ formatNumber(spot.photoCount) }}张照片</span>
                  </div>
                </div>
                <p
                  class="text-gray-600 dark:text-gray-300 text-sm line-clamp-2"
                >
                  {{ spot.description }}
                </p>
                <!-- 关联景点 -->
                <div v-if="spot.relatedSpot" class="mt-4 flex items-center text-sm">
                  <span class="text-gray-500 dark:text-gray-400 mr-2"
                    >关联景点：</span
                  >
                  <el-link
                    type="primary"
                    :underline="false"
                    @click.stop="$router.push(`/spots/${spot.relatedSpot.id}`)"
                  >
                    {{ spot.relatedSpot.name }}
                  </el-link>
                </div>
                <!-- 精选照片 -->
                <div v-if="spot.featuredPhotos && spot.featuredPhotos.length > 0" class="mt-4 grid grid-cols-4 gap-2">
                  <el-image
                    v-for="(photo, index) in spot.featuredPhotos.slice(0, 4)"
                    :key="index"
                    :src="photo"
                    class="w-full aspect-square object-cover rounded-lg cursor-zoom-in"
                    :preview-src-list="spot.featuredPhotos"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="flex justify-center mt-8">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[12, 24, 36, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 热门打卡地 -->
          <div
            class="hot-spots bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Star /></el-icon>
              热门打卡地
            </h3>
            <div class="space-y-4">
              <div
                v-for="spot in hotSpots"
                :key="spot.id"
                class="hot-spot-item group cursor-pointer"
                @click="handleSpotClick(spot)"
              >
                <div class="relative rounded-lg overflow-hidden mb-2">
                  <el-image
                    :src="spot.image"
                    class="w-full h-32 object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                  <div
                    class="absolute inset-0 bg-black/30 group-hover:bg-black/10 transition-colors"
                  ></div>
                </div>
                <h4
                  class="text-sm font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 line-clamp-1"
                >
                  {{ spot.name }}
                </h4>
                <div
                  class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"
                >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Camera /></el-icon>
                    {{ formatNumber(spot.checkInCount) }}次打卡
                  </span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><Star /></el-icon>
                    {{ spot.rating }}分
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 本月最佳摄影师 -->
          <div
            class="top-photographers bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Trophy /></el-icon>
              本月最佳摄影师
            </h3>
            <div class="space-y-4">
              <div
                v-for="(photographer, index) in topPhotographers"
                :key="photographer.id"
                class="photographer-item flex items-center gap-4 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
              >
                <div
                  class="rank-number w-6 h-6 rounded-full bg-primary-100 dark:bg-primary-900 text-primary-600 dark:text-primary-400 flex items-center justify-center text-sm font-medium"
                >
                  {{ index + 1 }}
                </div>
                <el-avatar :size="40" :src="photographer.avatar" />
                <div class="flex-1">
                  <div
                    class="text-sm font-medium text-gray-900 dark:text-white"
                  >
                    {{ photographer.name }}
                  </div>
                  <div class="text-xs text-gray-500 dark:text-gray-400">
                    {{ photographer.photoCount }}张作品
                  </div>
                </div>
                <div class="text-xs text-primary-600 dark:text-primary-400">
                  {{ photographer.likes }}获赞
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import {
  Search,
  Camera,
  Picture,
  Timer,
  Star,
  Trophy,
  Plus,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import service from "@/api/axios";

const router = useRouter();
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 筛选条件
const filters = reactive({
  category: "",
  spotId: "",
  sortBy: "popular",
});

// 打卡地数据
const photoSpots = ref([]);
const hotSpots = ref([]);
const topPhotographers = ref([]);
const spots = ref([]);

// 分类选项
const categories = [
  { label: "人气打卡地", value: "popular", type: "danger" },
  { label: "网红打卡点", value: "trending", type: "warning" },
  { label: "新晋打卡地", value: "new", type: "success" },
  { label: "自然风光", value: "nature", type: "info" },
  { label: "人文景观", value: "cultural", type: "" },
];

// 排序选项
const sortOptions = [
  { label: "最受欢迎", value: "popular" },
  { label: "最新发布", value: "newest" },
  { label: "打卡最多", value: "most_checkins" },
  { label: "照片最多", value: "most_photos" },
];

// 测试数据
const testPhotoSpots = [
  {
    id: 1,
    name: "贵港江滨公园",
    type: "人气打卡地",
    image: "/images/spots/spot1.jpg",
    bestTime: "清晨或黄昏",
    checkInCount: 2580,
    photoCount: 3650,
    description:
      "江滨公园沿江而建，是拍摄江景、日出的绝佳位置。清晨的薄雾与晚霞倒映在江面上，构成独特的景致。",
    relatedSpot: {
      id: 1,
      name: "贵港江滨公园",
    },
    featuredPhotos: [
      "/images/spots/spot1-1.jpg",
      "/images/spots/spot1-2.jpg",
      "/images/spots/spot1-3.jpg",
      "/images/spots/spot1-4.jpg",
    ],
    rating: 4.8,
  },
  // 这里原有的其他测试数据实例
];

// 测试数据 - 热门打卡地
const testHotSpots = [
  {
    id: 1,
    name: "贵港江滨公园日出",
    image: "/images/spots/spot1.jpg",
    checkInCount: 2580,
    rating: 4.8,
  },
  // 其他测试数据实例
];

// 测试数据 - 本月最佳摄影师
const testTopPhotographers = [
  {
    id: 1,
    name: "摄影师小王",
    avatar: "https://xsgames.co/randomusers/assets/avatars/male/32.jpg",
    photoCount: 128,
    likes: 3580,
  },
  {
    id: 2,
    name: "风光摄影师林林",
    avatar: "https://xsgames.co/randomusers/assets/avatars/female/44.jpg",
    photoCount: 96,
    likes: 2850,
  },
  {
    id: 3,
    name: "人像达人小美",
    avatar: "https://xsgames.co/randomusers/assets/avatars/female/68.jpg",
    photoCount: 75,
    likes: 2430,
  },
  {
    id: 4,
    name: "城市摄影师阿杰",
    avatar: "https://xsgames.co/randomusers/assets/avatars/male/75.jpg",
    photoCount: 64,
    likes: 1960,
  },
];

// 测试数据 - 景点列表
const testSpots = [
  { id: 1, name: "贵港江滨公园" },
  { id: 2, name: "贵港古镇" },
  { id: 3, name: "文创艺术园" },
];

// 获取分页数据
const displayedPhotoSpots = computed(() => {
  return photoSpots.value;
});

// 获取标签类型
const getTagType = (type) => {
  // 先从categories中查找
  const category = categories.find((c) => c.label === type);
  if (category?.type) return category.type;
  
  // 如果没有找到，使用固定的映射
  const typeMap = {
    "自然风光": "success",
    "城市风光": "info",
    "人文风情": "warning",
    "山水风光": "danger",
    "湖泊风光": "primary",
    "popular": "danger",
    "trending": "warning",
    "new": "success",
    "nature": "info",
    "cultural": ""
  };
  
  return typeMap[type] || "";
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 处理打卡地点击
const handleSpotClick = (spot) => {
  router.push(`/photography/${spot.id}`);
};

// 获取摄影打卡地数据
const fetchPhotoSpots = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      category: filters.category || undefined,
      spotId: filters.spotId || undefined,
      sortBy: filters.sortBy,
      keyword: searchQuery.value || undefined,
    };

    const res = await service.get('/public/photography/spots', { params });
    // 处理后端返回的分页数据结构
    if (res.data && Array.isArray(res.data)) {
      // 直接返回的是数组
      photoSpots.value = res.data;
      total.value = res.total || photoSpots.value.length;
    } else if (res.data && res.data.items) {
      // 返回的是带有items和total的对象
      photoSpots.value = res.data.items;
      total.value = res.data.total || photoSpots.value.length;
    } else {
      // 没有数据或格式不正确，使用测试数据
      photoSpots.value = testPhotoSpots;
      total.value = testPhotoSpots.length;
    }
  } catch (error) {
    console.error('获取摄影打卡地失败:', error);
    // 使用测试数据
    photoSpots.value = testPhotoSpots;
    total.value = testPhotoSpots.length;
  } finally {
    loading.value = false;
  }
};

// 获取景点列表
const fetchSpots = async () => {
  try {
    // 参考spots/index.vue的写法处理API请求
    const params = {
      pageSize: 100 // 获取足够多的打卡地点用于筛选
    };

    const res = await service.get('/public/spot/list', { params });
    console.log("景点列表API响应:", res);
    
    let allSpots = [];
    
    // 检查所有可能的数据结构模式
    if (res.data && res.data.content && Array.isArray(res.data.content)) {
      // 直接在res.data中有content数组
      console.log("从res.data.content直接获取数据");
      allSpots = [...res.data.content];
    } 
    else if (res.data && res.data.code === 200 && res.data.data && res.data.data.content && Array.isArray(res.data.data.content)) {
      // 嵌套在data.data.content
      console.log("从res.data.data.content获取数据");
      allSpots = [...res.data.data.content];
    }
    else if (res.data && res.data.data && res.data.data.records && Array.isArray(res.data.data.records)) {
      // MyBatis-Plus分页格式
      console.log("从res.data.data.records获取数据");
      allSpots = [...res.data.data.records];
    }
    else if (res.data && res.data.data && Array.isArray(res.data.data)) {
      // data直接是数组
      console.log("从res.data.data数组获取数据");
      allSpots = [...res.data.data];
    }
    else if (res.data && Array.isArray(res.data)) {
      // res.data直接是数组
      console.log("从res.data数组获取数据");
      allSpots = [...res.data];
    }
    else {
      console.error("未能识别的API响应格式:", res.data);
      spots.value = testSpots;
      return;
    }
    
    // 验证数据并提取需要的字段
    if (allSpots.length > 0) {
      spots.value = allSpots.map(item => ({ id: item.id, name: item.name }));
    } else {
      spots.value = testSpots;
    }
  } catch (error) {
    console.error('获取景点列表失败:', error);
    // 使用测试数据
    spots.value = testSpots;
  }
};

// 获取热门打卡地
const fetchHotSpots = async () => {
  // 不再调用API，而是从photoSpots中选择数据
  if (photoSpots.value && photoSpots.value.length > 0) {
    // 复制一份photoSpots数据
    const spots = [...photoSpots.value];
    // 按照打卡数量排序
    spots.sort((a, b) => (b.checkInCount || 0) - (a.checkInCount || 0));
    // 取前3个
    hotSpots.value = spots.slice(0, 3);
  } else {
    // 使用测试数据
    hotSpots.value = testHotSpots;
  }
};

// 获取最佳摄影师
const fetchTopPhotographers = async () => {
  try {
    const res = await service.get('/public/photography/top-photographers');
    // 检查是否有数据
    if (res.data && Array.isArray(res.data) && res.data.length > 0) {
      topPhotographers.value = res.data;
    } else if (res.data && res.data.items && Array.isArray(res.data.items) && res.data.items.length > 0) {
      topPhotographers.value = res.data.items;
    } else {
      console.log("摄影师数据为空，使用测试数据");
      // 没有数据，使用测试数据
      topPhotographers.value = testTopPhotographers;
    }
  } catch (error) {
    console.error('获取最佳摄影师失败:', error);
    // 使用测试数据
    topPhotographers.value = testTopPhotographers;
  }
};

// 处理分页变化
const handleSizeChange = () => {
  fetchPhotoSpots();
};

const handleCurrentChange = () => {
  fetchPhotoSpots();
};

// 监听筛选条件变化
watch([filters, searchQuery], () => {
  currentPage.value = 1; // 重置到第一页
  fetchPhotoSpots();
}, { deep: true });

// 页面加载时获取数据的顺序调整
onMounted(() => {
  // 先获取摄影打卡地
  fetchPhotoSpots().then(() => {
    // 然后基于打卡地数据获取热门打卡地
    fetchHotSpots();
  });
  // 获取最佳摄影师和景点列表
  fetchTopPhotographers();
  fetchSpots();
});
</script>

<style lang="scss" scoped>
.photography-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .card-header {
    @apply flex items-center justify-between;

    .header-actions {
      @apply flex items-center gap-4;
    }
  }
}
</style>
